package org.sdfc.model.dfc.collection

import scala.collection.mutable.ArrayBuffer

/** View of a RichCollection as a sequence of CollectionRow.
 *  <p>
 *  The point is to allow collection traversal to be done using
 *  sequence comprehensions syntax.
 */
class CollectionRows (
  /** RichCollection viewed as a sequence of CollectionRow. */
  private val coll : RichCollection
) {
  
  /** Consumes this, executing rf on each row.
   */
  def foreach(rf : CollectionRow => Unit) {
    var rowOpt = advance()
    while ( rowOpt.isDefined ) {
      rf( rowOpt.get )
      rowOpt = advance()
    }
  }
  
  /** Consumes this, accumulating the results of rf on each row in a new ArrayBuffer.
   */
  def map[T](rf : CollectionRow => T) : ArrayBuffer[T] = {
    val result = new ArrayBuffer[T]
    var rowOpt = advance()
    while ( rowOpt.isDefined ) {
      result += rf( rowOpt.get )
      rowOpt = advance()
    }
    result
  }
  
  
  /** Advances this and returns Some(row) if more is available,
   *  returns None if the end of the collection is reached.
   */
  protected def advance() : Option[CollectionRow] = coll.nextRow()
  
}
